<!--
* description: 追溯件更换信息查询-编辑
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
      @open="open"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :show-placeholder="comp.placeholder"
            :custom-obj="comp.customObj"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 24"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :data-to-object="comp.dataToObject"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/views/se/retroactivePartInquiry//mixins/formMixins'
import { orgApis } from '@/api/caseManagementQuery'

export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader'),
    mixButton: () => import('@/components/basicComponent/mixButton')
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    popupsState: { type: String, default: '' },
    dispatchNumber: { type: Object, default: () => ({}) }, // 派工单号

    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },

  data() {
    // const viewPageCode = 'bigAreaInfo-edit'
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.editSave(1),
          text: '提交',
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.editSave(0),
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.closeEdit(),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: 'comKey1',
          labelName: '门店编码：',
          codeField: 'dlrCode',
          isComponent: true,
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 8
        },
        {
          compKey: 'compKey2',
          labelName: '门店名称：',
          codeField: 'dlrFullName',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 8
        },
        {
          compKey: 'compKey3',
          labelName: 'VIN码：',
          codeField: 'vin',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey4',
          labelName: '派工单号：',
          codeField: 'repairOrderCode',
          // textField: "repairOrderCode",
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: true,
          disabled: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey6',
          labelName: '原追溯件编号：',
          codeField: 'partsCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMul: false,
          disabled: true,
          span: 8,
          isMust: true,
          isRequire: true
        },
        {
          compKey: 'compKey7',
          labelName: '新件编号：',
          codeField: 'newCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isMust: true,
          span: 8,
          isRequire: true
        },
        {
          compKey: 'compKey8',
          labelName: '追溯件类别：',
          codeField: 'replaceTypeCode',
          textField: 'replaceTypeName',
          component: () => import('@/components/org/commonSelect'),
          change: this.changeType,
          customObj: {
            api: orgApis.traceabilityCategoryQuery,
            defOptionFields: ['replaceTypeCode', 'replaceTypeName']
          },
          oFields: 'replaceTypeCode,replaceTypeName',
          type: 'dropdownList',
          disabled: true,
          isMust: true,
          span: 8,
          isRequire: true
        },
        {
          compKey: 'compKey9',
          labelName: '去向单位名称：',
          codeField: 'whereaboutsName',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isMust: true,
          span: 8,
          isRequire: false
        },
        {
          compKey: 'compKey10',
          labelName: '去向单位统一社会信用代码：',
          codeField: 'whereaboutsCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isMust: true,
          span: 8,
          isRequire: false
        },
        {
          compKey: 'compKey11',
          labelName: '上级电池编码：',
          codeField: 'parentCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isMust: true,
          span: 8,
          isRequire: false
        },
        {
          compKey: "compKey12",
          labelName: "备件编号：",
          codeField: "partNo",
          textField: "partNo",
          component: () => import("@/components/org/LookupValue"),
          options: [],
          oFields: 'partNo,partNo',
          type: "dropdownList",
          disabled: true,
          isMust: true,
          span: 8,
          isRequire: true,
        },
      ],

      // 标题
      textMap: {
        edit: '追溯件更换信息详情',
        add: '追溯件更换信息新增',
        detail: '追溯件更换信息编辑'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        dlrFullName: '',
        dlrCode: '',
        dlrId: '',
        vin: '',
        repairOrderCode: '',
        partsCode: '',
        newCode: '',
        replaceTypeCode: '',
        replaceTypeName: '',
        whereaboutsName: '',
        whereaboutsCode: '',
        parentCode: '',
        isCommit: '',
        partsReplaceId: '',
        partNo: "", //追溯件备件编号
        partName: "",
      }
    }
  },

  watch: {
    'formField.repairOrderCode'(val) {
      if (val) {
        this.formField.partNo="";//每次有变化，清空备件编号
        this.queryFindDetail()
      } else {
        this.formField.dlrCode = ''
        this.formField.dlrFullName = ''
        this.formField.dlrId = ''
        this.formField.vin = ''
        this.formField.partNo = "";//如果为空则清空
        this.tableComponents[10].disabled = true;//如果为空则禁用
      }
    }
  },

  methods: {
    // 新增 查询故障编号
    queryNumber(val){
      // 修改则带出
      if(this.popupsState == "detail"){
        this.formField.partNo=this.dynamicEditRowData.partNo;
      }
      
      const queryObj = {
          type: "mutation",
          apiConfig: {
            ServiceCode: "selectPartList",
            APIUrl:
              "/mp/e3sh/aftersale/WorkOrderManagementService/selectPartList.do",
          },
          variables: {
            repairOrderId: val,
          },
        };
        var paramD = this.$getParams(queryObj);
        this.$requestAPI(paramD).then((response) => {
          this.tableComponents[10].options=response.rows
        });
    },
    // 追溯件类别发生改变则触发
    changeType(val) {
      if (val === 'M') {
        this.tableComponents[7].isRequire = true
        this.tableComponents[8].isRequire = true
        this.tableComponents[9].isRequire = true
      } else if (val === 'P') {
        this.tableComponents[7].isRequire = true
        this.tableComponents[8].isRequire = true
        this.tableComponents[9].isRequire = false
      } else {
        this.tableComponents[7].isRequire = false
        this.tableComponents[8].isRequire = false
        this.tableComponents[9].isRequire = false
      }
      this.tableComponents[7].compKey = this.tableComponents[7].compKey + '1'
      this.tableComponents[8].compKey = this.tableComponents[8].compKey + '1'
      this.tableComponents[9].compKey = this.tableComponents[9].compKey + '1'
    },
    closeEdit() {
      this.curPopupsVisible = false
      this.$emit('close', false)
    },

    open() {
      if (this.popupsState == 'edit') { // 修改
        this.queryTraceabDetails()
        for (const k in this.tableComponents) {
          this.tableComponents[k].disabled = true
        }
        this.tableButtons = []
      } else if (this.popupsState == 'add') { // 新增
        this.formField.repairOrderCode = this.dispatchNumber.repairOrderCode// 拿到派工单号
        this.tableComponents[3].disabled = true
        this.tableComponents[4].disabled = false
        this.tableComponents[5].disabled = false
        this.tableComponents[6].disabled = false
        this.tableComponents[7].disabled = false
        this.tableComponents[8].disabled = false
        this.tableComponents[9].disabled = false
        this.tableButtons = [
          // {
          //   compKey: 'btnKey4',
          //   type: 'primary',
          //   size: 'small',
          //   icon: 'iconfont  icon-preservation',
          //   clickEvent: () => this.editSave(1),
          //   text: '提交',
          //   disabled: false,
          //   position: 'right'
          // },
          {
            compKey: 'btnKey5',
            type: 'primary',
            size: 'small',
            icon: 'iconfont  icon-preservation',
            clickEvent: () => this.editSave(0),
            disabled: false,

            text: '保存',
            position: 'right'
          },
          {
            compKey: 'btnKey6',
            size: 'small',
            icon: 'iconfont  icon-cancel',
            clickEvent: () => this.closeEdit(),
            text: this.$t('sys.button.cancel') // 取消
          }
        ]
      } else if (this.popupsState == 'detail') {
        this.queryTraceabDetails()
        // this.formField.partNo=this.dynamicEditRowData.partNo;
        this.tableComponents[3].disabled = true //禁用派工单号
        this.tableComponents[4].disabled = false
        this.tableComponents[5].disabled = false
        this.tableComponents[6].disabled = false
        this.tableComponents[7].disabled = false
        this.tableComponents[8].disabled = false
        this.tableComponents[9].disabled = false
        this.tableComponents[10].disabled = false;
        this.tableButtons = [
          // {
          //   compKey: 'btnKey7',
          //   type: 'primary',
          //   size: 'small',
          //   icon: 'iconfont  icon-preservation',
          //   clickEvent: () => this.editSave(1),
          //   text: '提交',
          //   disabled: false,
          //   position: 'right'
          // },
          {
            compKey: 'btnKey8',
            type: 'primary',
            size: 'small',
            icon: 'iconfont  icon-preservation',
            clickEvent: () => this.editSave(0),
            disabled: false,
            // text: this.$t('sys.button.save') /* 保存*/,
            text: '保存',
            position: 'right'
          },
          {
            compKey: 'btnKey9',
            size: 'small',
            icon: 'iconfont  icon-cancel',
            clickEvent: () => this.closeEdit(),
            text: this.$t('sys.button.cancel') // 取消
          }
        ]
      }
    },

    // 带入派工单号进行查询
    queryFindDetail() {
      this.tableComponents[10].disabled = false;
      const that = this
      const info = {}
      info.repairOrderCode = this.formField.repairOrderCode
      const queryObj = {
        // api配置
        apiConfig: orgApis.findDetailByRepairOrderCode,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: info
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          that.formField.dlrCode = response.rows[0].dlrCode
          that.formField.dlrFullName = response.rows[0].dlrFullName
          that.formField.dlrId = response.rows[0].dlrId
          that.formField.vin = response.rows[0].vin
          that.queryNumber(response.rows[0].repairOrderId);
        }
      })
    },

    // 详情
    queryTraceabDetails() {
      const info = {}
      info.partsReplaceId = this.dynamicEditRowData.partsReplaceId
      const queryObj = {
        // api配置
        apiConfig: orgApis.traceabilityDetails,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: info
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          for (const k in this.formField) {
            this.formField[k] = response.rows[0][k]
          }
          this.changeType(this.formField['replaceTypeCode'])
        }
      })
    },

    // 新增保存
    editSave(num) {
      this.$utils.validataMoth(this, 'validpopup')
      if (!this.valid) {
        return
      }
      const that = this
      this.formField.isCommit = num
      this.formField.partsReplaceId = this.dynamicEditRowData.partsReplaceId
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.maintenanceOfTraceableParts,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      if (this.popupsState == 'detail') {
        queryObj.apiConfig = orgApis.updateTraceableParts
      } else if (this.popupsState == 'add') {
        queryObj.apiConfig = orgApis.maintenanceOfTraceableParts
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      if (this.formField.repairOrderCode == '') {
        this.$message({
          message: '派工单号不能为空',
          type: 'warn',
          duration: 1000
        })
      } else {
        that.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            that.$message({
              message: this.$t('sys.tips.esTip5') /* 保存成功*/,
              type: 'success',
              duration: 1000
            })
            that.curPopupsVisible = false
            that.$nextTick(() => {
              // that.$parent.queryTable(1);
              that.$parent.open()
            })
            this.$emit('numRefresh')
          } else {
            // 保存失败
            that.$message({
              message: response.msg,
              type: 'warn',
              duration: 1000
            })
          }
          that.curPopupsVisible = false
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan {
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

